<template>
	<!-- 	// coach 是否有权编辑 //rollCoa-->
	<div class="index_Coach">

		<section class="van-doc-demo-section demo-contact-card">
			<div class="van-doc-demo-title t-center pad clPadBtm">

				<van-cell-group class='searchCon' v-if='coach && edit'>
					<van-field class="marBtm" v-show='coach' @focus='showPicker=true' v-model="keyVal" left-icon='search' placeholder="请输入你要搜索内容" />
				</van-cell-group>
				<van-field v-if='edit' name="picker" v-model="coach?value:keyVal" autosize @focus='showPicker=true' :placeholder="$H(this,'selectTit')+targetTitName">
					<template #button>
						<van-button @click='addListFn' size="small" type="primary">Add</van-button>
					</template>
				</van-field>
				<van-popup :overlay='false' class="searchPop" :safe-area-inset-bottom='true' :get-container='".index_Coach"'
				 v-model="showPicker">
					<van-picker v-if='coach?queryCoachList.length:queryAthletesList.length' show-toolbar allow-html :columns="coach?queryCoachList:queryAthletesList"
					 @confirm="onConfirm" @cancel="showPicker = false" />
				</van-popup>

				<p class="pad">{{targetTitName}}</p>
			</div>
			<div class="van-doc-demo-block">
				<!-- <h3 v-show='!edit' class="van-doc-demo-block__title t-center pad">{{$route.query.uts}}</h3> -->

				<div class="vanList" v-if='athleteCoachList.length'>
					<div :key='i' v-for="(list , i) in  athleteCoachList">

						<div role="button" tabindex="0" :class="' list_box van-cell flex-box van-cell--clickable van-cell--center van-cell--borderless van-contact-card van-contact-card--add' + 'list_box' + i">
							<van-icon size='50' :name="list.headImg?list.headImg:'contact'" class="avatar" />
							<div class="van-cell__value van-cell__value--alone van-contact-card__value">
								<div>{{ list | FilterName(['lastName','firstName'])}}</div>
								<div>{{list.tcName}}</div>
							</div>
							<van-icon class="iconRig" @click='dialogShowFn(list,0,i)' size='40' name="success" 
							:style='bgColor(list)' 
							/>
							<van-icon class="iconRig " @click='dialogShowFn(list,1,i)' size='40' name="weapp-nav" />
						</div>
						<van-grid v-show="list.edit ">
							<van-grid-item :text="$t('app.TrainDetailsEdit.time')" class='lft' />
							<van-grid-item style='flex-basis:75%'>

								<van-cell :style='list.statu?"background:rgba(229,230,231,.7)":""' size="20" @click='(e)=>showTimerPopFn(list,i)'
								 :is-link='!list.statu' :arrow-direction="!list.statu&&!list.showTimer?'':'down'">
									{{list[!list.statu?'_workingHour':'workingHour_']?list[!list.statu?'_workingHour':'workingHour_']:0}}</van-cell>
									
								<van-popup v-model="list.showTimer" position='bottom' :overlay='true' :lazy-render='false'>
									<van-picker :title="$t('app.TrainDetailsEdit.time')" show-toolbar :columns="columns" @cancel='list.showTimer = false'
									 @confirm="(e)=>confirmTimer(e,list)" />

								</van-popup>
							</van-grid-item>
							<van-grid-item :text="$t('app.TrainDetailsEdit.reason')" class='lft' />
							<van-grid-item style='flex-basis:75%'>
								<van-cell size="20" @click='showSheet=true;indList=i' is-link :arrow-direction="showSheet?'down':''" :value="list[!touchList.statu?'_reason':'reason_']">
								</van-cell>
							</van-grid-item>
						</van-grid>

					</div>
				</div>
				<van-empty v-else description="No Data" />

				<van-popup :setValues='selSeason' lazy-render v-model="showSheet"   position="bottom" :safe-area-inset-bottom='true'>
					<van-picker :title="touchList.statu?'Absent Reason':'Irregular attendance reason'" show-toolbar :columns="touchList.statu?ABSENT_REASSON:LEAVE_REASSON"
					 @confirm="onSelect" @cancel="showSheet=false" />
				</van-popup>
			</div>

		</section>
	</div>
</template>

<script>
	import {
		parseTime
	} from '@/utils';
	const utilsDay = (60 * 60 * 24 * 1000) * 3;

	export default {
		name: 'LessonCoach',

		data() {
			return {
				// 处理控件显示的时间格式
				pageEdit: false,
				value: '',
				signInTime: new Date(),
				keyVal: '',
				indList: 0,
				userType: '',
				showTimer: false,
				showPicker: false,
				show: false,
				dialogShow: false,
				showSheet: false,
				touchList: {},
				status: 0,
				statu: 0,

				ABSENT_REASSON: [],
				LEAVE_REASSON: [],
				selSeason: 'None',
				actions: {
					name: 'None1',
					subname: '描述信息',
					value: 'None',
				},
				actionsInd: [],
				parseTime
			};
		},
		mounted() {
			console.log("va", this)
			this.fetchData()

			this.$route.meta.onClickRight = this.saveCheck
		},
		updated() {

		},
		computed: {
			key() {
				return this.$route.name !== undefined ? this.$route.name + new Date() : this.$route + new Date();
			},
			
			//檢驗是否可以點名
			allowCheck() {
				//點名時間應該為上課前2小時后, 直至有人在account report那裡點了coach cut－off 那麼 coach才不能edit 點名數據
				let lessonInfo = this.$store.state.train.lessonInfo
				return lessonInfo?(new Date(lessonInfo.upperDate +" "+lessonInfo.startTime ).getTime() - new Date().getTime() <=(1000*3600*2)):false
			},
			columns() {
				var tRR = []
				for (var i = 0; i <= 10; i += 0.5) {
					tRR.push(i)
				}
				return tRR
			},
			athleteCoachList(val) {
				this.$store.state.trainLessCoach[this.targetStr].map(lis => {
					if(lis.status !=='ABSENT'&&lis._reason&&lis._reason!=='None'){
						lis.status  = 'LAST_EARLYLEAVE'
					}
					// if(lis.status ==='NOTSIGN'){
					// 	let resultAthleteCoach = this.$store.state.trainLessCoach.resultAthleteCoach.lesson
					// 	lis._workingHour= resultAthleteCoach.upperDuration 
					// 	lis.workingHour_= resultAthleteCoach.upperDuration 
					// }
					!lis._reason?lis._reason = 'None':'';
					!lis.reason_?lis.reason_ = 'None':'';
					
					//lis._signInTime = new Date(lis.signInTime)
					return lis
				})
				console.log("list thelete",this.$store.state.trainLessCoach[this.targetStr])
				return this.$store.state.trainLessCoach[this.targetStr]
			},
			athleteRollParams() {
				return this.$store.state.trainLessCoach.athleteRollParams
			},
			// lessonAthleteList() {
			// 	return this.$store.state.train.lessonAthleteList
			// },
			// lessonCoachList() {
			// 	return this.$store.state.train.lessonCoachList
			// },
			queryAthletesList(name) {
				return this.$store.state.trainLessCoach.queryAthletesList
			},
			queryCoachList(name) {
				return this.$store.state.trainLessCoach.queryCoachList
			},
		},
		watch: {
			'$route'(to, from, next) {
				console.log("是多少", from)
			},
			keyVal(val) {
				this.keyValList = ''
				if (this.coach) {
					this.queryCoachListFn(val)
				} else {
					this.queryAthletesListFn(val)
				}
			},
			// touchList(val) {
			// 	if (!this.dialogShow && val) {
			// 		this.athleteCoachList.map((item) => {
			// 			if (val.id === item.id && val !== item) {console.log('route', query, e)
			// 				return item = val
			// 			}
			// 		})
			// 	}
			// },
			selSeason(val) {
				if(this.indList>=0){
					this.$set(this.athleteCoachList[this.indList],'status', !this.statu? val === 'None' ? 'CHECK-IN' : 'LAST_EARLYLEAVE' : 'ABSENT')
				}
			}
		},
		beforeCreate() {
			let e = this
			let query = e.$route.query
			//console.log('route', query, e)
			e.coach = query.coach == 1 || false
			e.targetTitName = this.$H(this, e.coach ? 'particiTool' : 'sport')
			e.targetStr = 'lesson' + (e.coach ? 'Coach' : 'Athlete') + 'List'
			e.edit = query.edit == 1
			//e.pageEdit = query.edit
			e.rollCall = query.rollCall || query.rollCall === 'NO'
			e.lessonId = query.lessonId
			this.$store.dispatch('trainLessCoach/athleteRollParams', {
				lessonId: e.lessonId
			})

			this.$ajax.get('/roll_call/obtain/setting', {
				params: {
					code: 'LEAVE_REASSON'
				}
			}, (res) => {
				e.LEAVE_REASSON = [{
					value: 'None',
					text: 'None'
				}]
				res.result.map(li => {
					//that.LocList.push(li.typeName) 
					e.LEAVE_REASSON.push({
						value: li.typeName,
						text: li.typeName
					})
				})
			}, () => {})

			this.$ajax.get('/roll_call/obtain/setting', {
				params: {
					code: 'ABSENT_REASSON'
				}
			}, (res) => {
				e.ABSENT_REASSON = [{
					value: 'None',
					text: 'None'
				}]
				res.result.map(li => {
					//that.LocList.push(li.typeName) 
					e.ABSENT_REASSON.push({
						value: li.typeName,
						text: li.typeName
					})
				})
			}, () => {})


		},
		created() {
			var that = this
			//console.log('as', this.$store.getters)
		},
		methods: {
			bgColor(list){
						  let lesson = this.$store.state.trainLessCoach.resultAthleteCoach.lesson
						  return {
						   	background:list.status=="CHECK-IN"||list.status=="LAST_EARLYLEAVE" ?"#1989fa":""}
			   },
			showTimerPopFn(e, list) {
				this.indList = list
				if (!e.statu) {
					this.$set(e, "showTimer", true)
				}

			},
			signTimeFn(list) {
				if (list._signInTime) {
					list._signInTime
					//this.$set(list,'signInTime',parseTime(list._signInTime))
				} else {}
				this.$set(list, '_signInTime', list.signInTime)
				return list.signInTime
			},
			formatDate(dates) {
				return parseTime(dates.date ? dates.date : dates)
			},
			//搜索 編輯
			queryAthletesListFn(name) {
				this.$store.dispatch('trainLessCoach/queryAthletesList', {
					name,
					type: 'athlete'
				})
			},
			queryCoachListFn(name) {
				this.$store.dispatch('trainLessCoach/queryCoachList', {
					name,
					type: 'coachs'
				})
			},
			pushAthletesList(name) {
				this.$store.dispatch('trainLessCoach/pushqueryAthletesList', { ...name
				})
			},
			pushqueryCoachList(name) {
				this.$store.dispatch('trainLessCoach/pushqueryCoachList', { ...name
				})
			},
			popupShowFn() {
				//this.showPicker = !this.showPicker
			},
			onConfirm(List) {
				//debugger
				this.keyValList = List.value;
				this.keyList = List;
				this.keyVal = List.text;
				this.showPicker = false;
			},
			onSelect(item) {
					
				// 默认情况下点击选项时不会自动收起
				// 可以通过 close-on-click-action 属性开启自动收起
				console.log('sadsa', item.value, this.athleteCoachList, this.indList)

				this.selSeason = item.value
				//this.indList.reason = item.value
				this.athleteCoachList[this.indList][!this.athleteCoachList[this.indList].statu?"_reason":'reason_']=item.value
				
				this.$set(this.athleteCoachList, this.indList,this.athleteCoachList[this.indList])
				this.showSheet = false;
				 //debugger
				this.confirmDialog(this.athleteCoachList[this.indList])
               
			},
			//修改 签到信息 提交 store 
			confirmDialog(list) {
				this.$store.dispatch('user/getLoction')
				this.$set(this,'selSeason',list[this.statu?'reason_':'_reason']) 
				this.$set(list, "status",!status&&list['_reason']&&list['_reason']!=='None'? 'LAST_EARLYLEAVE':this.status )
				 //debugger
				//this.touchList.reason = this.selSeason //原因
				//list.status = this.status //状态 迟到还是缺席 “状态 CHECK-IN=正常 LAST_EARLYLEAVE=迟到或早退，ABSENT=缺席“
				let {
					id,
					signLocation,
					status,
					signCoordinate,
					[!list.statu?"_workingHour":'workingHour_']:workingHour,
					[!list.statu?"_reason":'reason_']:reason
				} = list
				let athleteRollCall = {
					id,
					signCoordinate,
					signLocation,
					status,
					workingHour,
					reason
				}
				 //debugger
				this.$store.dispatch('trainLessCoach/athleteRollParams', {
					athleteRollCall
				})
				console.log("athleteRollCallathleteRollCall ", athleteRollCall)
			},
			//修改 當前角色 時間
			confirmTimer(e, list) {
				this.$set(list, "showTimer", false)
				this.$set(list, !list.statu?"_workingHour":'workingHour_', e)
				//this.$set(list,"signInTime",parseTime(list._signInTime))
				this.confirmDialog(list)
			},
			saveCheck(e, _that) {
				var that = this
				
				if (this.allowCheck) {
					let tabNav = this.$refs.tabNav
					// this.$store.dispatch('user/updateTabInfo', {
					// 	backPath: {
					// 		name: ''
					// 	},
					// 	rightText: that.$t('app.Common.rightText')
					// })
					//debugger
					
					this.$store.dispatch('trainLessCoach/athleteCheck', {
						data: this.athleteRollParams,
						athlete: !this.coach ? 'athlete' : 'coach',
						_this:this
					})
				} else {
					
					this.$notify({
						type: 'warning',
						message: 'User can take attendance 2 hours before lesson start time!'
					})
				}
				//that.pageEdit = !that.pageEdit
				//_that.rightText = that.$H(this, that.pageEdit ? '_rightText' : 'rightText')

			},
			dialogShowFn(list, status, ind) {
				let langCh = window.localStorage.getItem('lang') ==='en'
				this.indList = ind
				this.statu = status
				this.status = status ? 'ABSENT' : 'CHECK-IN'

				if (this.allowCheck) {
					this.$set(list, "edit", !list.edit)
					this.$set(list, "statu", status)
					this.dialogShow = true
					//debugger
					this.touchList = list
				} else {
					
					this.$notify({
						type: 'warning',
						message: require('@js/lang/requireCode').default[2039][langCh?0:1]  
					})
				}

			},
			fetchData() {
				this.$store.dispatch("trainLessCoach/" + this.targetStr, {
					lessonId: this.lessonId
				})
			},
		},

	}
</script>
<style lang="less">
	.index_Coach {
		.van-grid-item__content {
			padding: 0;
		}

		.lft {
			flex-basis: 25%;

			>div {
				background: @blue;

				span {
					color: @white
				}
			}
		}
	}
</style>
<style lang='less' scoped="scoped">
	.index_Coach {
		overflow: initial;
		position: relative;

		.van-doc-demo-title {
			background: @gray-3;
		}

		.van-calendar__header-title {
			//display: none;
		}

		.avatar {
			background: @gray;
			color: @white;
			border-radius: 50%;
			overflow: hidden;

		}

		.iconRig {
			padding: 10px;
		}

		.searchPop {
			position: absolute;
			top: 200px;
			/* margin-top: 45px; */
			width: 100%;
			height: auto;
			max-height: initial;
		}

		.vanList {
			padding: 0;
			/* ::first-child{
				border-top: 1px solid #f7f8fa;
			} */

			.list_box {
				padding: 0;
			}

			.van-icon-success {
				background: @gray-4;

			}

			.van-icon-weapp-nav {
				padding: 10px;
				height: 60px;
				width: 30px;
				padding: 0;
				position: relative;

				&::before {
					transform: rotate(90deg);
					height: 18px;

					width: 60px;
					display: block;
					position: absolute;
					left: -5px;
					top: 20px;
					text-align: center;
					right: 0;
					bottom: 0;
				}
			}
		}

	}
</style>
